package com.dlc.shop.api.controller;

import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.dlc.shop.bean.bo.PayInfoResultBO;
import com.dlc.shop.bean.enums.PayEntry;
import com.dlc.shop.bean.enums.PayStatus;
import com.dlc.shop.bean.model.PayInfo;
import com.dlc.shop.bean.model.RefundInfo;
import com.dlc.shop.common.enums.PayType;
import com.dlc.shop.common.response.ResponseEnum;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.manager.impl.PayManager;
import com.dlc.shop.service.OrderRefundService;
import com.dlc.shop.service.PayInfoService;
import com.dlc.shop.service.RefundInfoService;
import com.dlc.shop.user.common.service.UserBalanceService;
import com.dlc.shop.user.common.service.UserLevelService;
import io.swagger.v3.oas.annotations.Hidden;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Objects;

/**
 * @author LGH
 */
@Hidden
@RestController
@RequestMapping("/notice/pay")
@AllArgsConstructor
public class PayNoticeController {

    private final PayManager payManager;

    private final PayInfoService payInfoService;

    private final UserLevelService userLevelService;

    private final UserBalanceService userBalanceService;

    private final RefundInfoService refundInfoService;
    private final OrderRefundService orderRefundService;


    /**
     * 支付异步回调
     */
    @RequestMapping("/{paySysType}/{payEntry}/{payType}")
    public ServerResponseEntity<String> notice(HttpServletRequest request,
                                               @PathVariable("paySysType") Integer paySysType,
                                               @PathVariable("payEntry") Integer payEntry,
                                               @PathVariable("payType") Integer payType,
                                               @RequestBody(required = false) String data) throws WxPayException, UnsupportedEncodingException, AlipayApiException {

        PayInfoResultBO payInfoResultBO = payManager.validateAndGetPayInfo(paySysType, request, PayType.instance(payType), data);
        if (Objects.nonNull(payInfoResultBO.getIsAliRefund()) && payInfoResultBO.getIsAliRefund()) {
            RefundInfo refundInfo = refundInfoService.getOne(new LambdaQueryWrapper<RefundInfo>().eq(RefundInfo::getRefundId, payInfoResultBO.getRefundSn()));
            // 支付宝退款回调
            if (!payInfoResultBO.getIsPaySuccess()) {
                if (StrUtil.isNotBlank(payInfoResultBO.getCallbackContent())) {
                    refundInfo.setCallbackContent(payInfoResultBO.getCallbackContent());
                    refundInfo.setCallbackTime(new Date());
                    refundInfoService.updateById(refundInfo);
                }
            } else {
                refundInfoService.refundSuccess(refundInfo);
            }
            return ServerResponseEntity.success(payInfoResultBO.getSuccessString());
        }

        // 校验订单参数异常
        if (!payInfoResultBO.getIsPaySuccess()) {
            return ServerResponseEntity.success(null);
        }

        PayInfo payInfo = payInfoService.getOne(new LambdaQueryWrapper<PayInfo>().eq(PayInfo::getPayNo, payInfoResultBO.getPayNo()));

        // 已经支付
        if (Objects.equals(payInfo.getPayStatus(), PayStatus.PAYED.value()) || Objects.equals(payInfo.getPayStatus(), PayStatus.REFUND.value())) {
            return ServerResponseEntity.success(payInfoResultBO.getSuccessString());
        }
        // 支付金额不对
        if (!Objects.equals(payInfo.getPayAmount(), payInfoResultBO.getPayAmount()) && !Objects.equals(payInfo.getPayType(), PayType.PAYPAL.value())) {
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }
        if (Objects.equals(payEntry, PayEntry.ORDER.value())) {
            return payInfoService.noticeOrder(payInfoResultBO, payInfo,paySysType);
        }
        else if (Objects.equals(payEntry, PayEntry.RECHARGE.value())) {
            return userBalanceService.noticeRecharge(payInfoResultBO, payInfo);
        }
        else if (Objects.equals(payEntry, PayEntry.VIP.value())) {
            return userLevelService.noticeBuyVip(payInfoResultBO, payInfo);
        }else if (Objects.equals(payEntry, PayEntry.ORDER_SETTLEMENT_BY_REFUND.value())) {
            // 订单部分退款导致结算处理(通联支付独有)
            return orderRefundService.settlementAllinpayOrderByRefund(payInfoResultBO, payInfo);
        }else if (Objects.equals(payEntry, PayEntry.ORDER_SETTLEMENT.value())) {
            // 订单结算(通联支付独有)
            return payInfoService.settlementAllinpayOrder(payInfoResultBO, payInfo);
        }

        return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
    }

}
